package cn.lyn4ever.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.*;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

public class RequestUtils {
    private static Logger logger;

    /**
     * 对网站进行get请求
     *
     * @param urlString
     * @param paramsMap
     * @return
     * @throws Exception
     */
    public static String sendGet(String urlString, Map<String, String> paramsMap) throws Exception {
        String params = "";
        if (null != paramsMap && paramsMap.size() > 0) {
            params = formatParams(paramsMap);//格式化参数
        }
        //格式化地址
        String url;
        if ("".equals(params)) {
            url = urlString;
        } else {
            url = urlString + "?" + params;
        }
        StringBuffer sb = new StringBuffer("");

        BufferedReader br = null;
        try {

            System.out.println(url);
            URL toUrl = new URI(url).toURL();
            URLConnection connection = toUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();

            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;
            while (null != (line = br.readLine())) {
                sb.append(line);
            }
//            logger.info("发送了一次get请求:" + url);
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    public static String sendPost(String url, Map<String, String> paramsMap) {
        String params = "";
        if (null != paramsMap) {
            params = formatParams(paramsMap);
        }


        URL toUrl = null;
        URLConnection conn;
        StringBuffer sb = new StringBuffer();
        try {
            toUrl = new URI(url).toURL();
            conn = toUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            //得到输出流,往请求通道里写入参数
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
            pw.write(params);
            pw.flush();
            pw.close();

            //得到从网络发回来的输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while (null != (line = br.readLine())) {
                sb.append(line);
            }
            br.close();
            logger.info("发送了一次post请求:" + url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 格式化参数
     *
     * @param paramsMap
     * @return
     */
    private static String formatParams(Map<String, String> paramsMap) {

        String params = "";
        Set<String> keys = paramsMap.keySet();
        for (String key : keys) {
            params += key + "=" + paramsMap.get(key) + "&";
        }
        System.out.println(params);
        //最后一个是&,不取
        return params.substring(0, params.length() - 1);
    }


    public static void upload(String url, String filePath) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        try {
            HttpPost httppost = new HttpPost(url);

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
            httppost.setConfig(requestConfig);

            FileBody bin = new FileBody(new File(filePath));
            StringBody comment = new StringBody("This is comment", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("comment", comment).build();

            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String responseEntityStr = EntityUtils.toString(response.getEntity());
                    System.out.println(responseEntityStr);
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }







    // 上传多媒体文件到微信服务器
    public static final String upload_media_url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
    /**
     * 上传多媒体文件到微信服务器<br>
     * @see http://www.oschina.net/code/snippet_1029535_23824
     * @see http://mp.weixin.qq.com/wiki/index.php?title=上传下载多媒体文件
     *
     * @author qincd
     * @date Nov 6, 2014 4:11:22 PM
     */
    public static String uploadMediaToWX(String filePath,String type,String accessToken) throws IOException{
        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }

        String url = upload_media_url.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");

        // 设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="
                + BOUNDARY);

        // 请求正文信息

        // 第一部分：
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // ////////必须多两道线
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
                + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");

        byte[] head = sb.toString().getBytes("utf-8");

        // 获得输出流
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(head);

        // 文件正文部分
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();

        // 结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线

        out.write(foot);

        out.flush();
        out.close();

        /**
         * 读取服务器响应，必须读取,否则提交不成功
         */
        try {
            // 定义BufferedReader输入流来读取URL的响应
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            conn.disconnect();


            System.out.println(buffer.toString());
            return  buffer.toString() ;
        } catch (Exception e) {
//            log.error("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        return null;
    }







}
